<?php

require_once "./class/DB.class.php";

class Object {

	protected $_conn		= null;
	public $_identifier	= false;

	public function __construct( $identifier = null ) {
		
		$this->_conn	= new DB();
		
		if ( $identifier ) {
			$this->_identifier	= $this->load( $identifier );
		}
	
	}
	
	public function load( $identifier = null ) {
	
		$query	= "SELECT * FROM `" . strtolower(get_class( $this )) . "` "
				. "WHERE `_identifier` = " . $identifier . " "
				. "LIMIT 1";
		$this->_conn->query( $query );
		
		if ( $this->_conn->count() > 0 ) {
			$result	= $this->_conn->fetch();
			foreach( $result as $key => $value ) {
				if ( property_exists( $this, $key ) ) {
					$this->$key	= $value;
				}
			}
			return $result['_identifier'];
		}
		
		return false;
	
	}
	
	public function save( $values = array() ) {
		
		if ( $this->_identifier ) {
			$queryPattern	= "UPDATE `" . strtolower(get_class( $this )) . "` SET %s WHERE `_identifier` = " . $this->_identifier;
		} else {
			$queryPattern	= "INSERT INTO `" . strtolower(get_class( $this )) . "` SET %s";
		}
		
		foreach( $values as $key=>$value ) {
			$values[$key]	= "`$key`='" . addslashes( stripslashes( $value ) ) . "'";
		}
		
		$query	= sprintf( $queryPattern, implode( ", ", $values ) );
		if ( $this->_conn->query( $query ) ) {
			if ( !$this->_identifier ) {
				$this->_identifier	= $this->_conn->getInsertedId();
			}
			return true;
		} else {
			return false;
		}
	
	}

	function destroy() {
	
		if ( $this->_identifier ) {
			$query	= "DELETE FROM `" . strtolower(get_class( $this )) . "` "
					. "WHERE `identifier` = " . $this->_identifier . " "
					. "LIMIT 1";
			$this->_conn->query( $query );
		}
	
	}

}

?>